//
//  PageContentView.swift
//  liveDemo
//
//  Created by satoshi_uma on 2020/10/21.
//  Copyright © 2020 satoshi_uma. All rights reserved.
//

import UIKit

protocol PageContentViewDelegate: class {
    func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, tagetIndex: Int)
}

private let ContentCellIdD = "CellID"

class PageContentView: UIView {
    private var childVcs: [UIViewController]
    private var startContentOffset: CGFloat = 0
    private weak var parentViewController: UIViewController?
    private var isForbidScrollDelegate: Bool = false
    weak var delegate: PageContentViewDelegate?

    init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) {
        self.childVcs = childVcs
        self.parentViewController = parentViewController

        super.init(frame: frame)

        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:)没有被执行。")
    }

//    懒加载
    private lazy var collectionView: UICollectionView = { [weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)! // 强制解包
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0

        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.delegate = self

        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellIdD)

        return collectionView
    }()
}

extension PageContentView {
    private func setupUI() {
        for childVc in childVcs {
            parentViewController?.addChild(childVc)
        }

        addSubview(collectionView)
        collectionView.frame = bounds
    }
}

// UICollectionViewDataSource
extension PageContentView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        创建 cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellIdD, for: indexPath)

        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }

//        给 cell 设置内容
        let childVc = childVcs[indexPath.item]

        childVc.view.frame = cell.contentView.bounds
        cell.contentView.addSubview(childVc.view)

        return cell
    }
}

// UICollectionViewDelegate
extension PageContentView: UICollectionViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        startContentOffset = scrollView.contentOffset.x
        isForbidScrollDelegate = false
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        判断是否是点击事件
        if isForbidScrollDelegate {
            return
        }

        var progress: CGFloat = 0
        var sourceIndex: Int = 0
        var tagetIndex: Int = 0

        let currentOffsetX = scrollView.contentOffset.x
 
        if currentOffsetX > startContentOffset {
//            print("左滑动")
            progress = currentOffsetX / SCREEN_WIDTH - floor(currentOffsetX / SCREEN_WIDTH)
            sourceIndex = Int(currentOffsetX / SCREEN_WIDTH)

            tagetIndex = sourceIndex + 1

            if tagetIndex >= childVcs.count {
                tagetIndex = childVcs.count - 1
            }

            if currentOffsetX - startContentOffset == SCREEN_WIDTH {
                progress = 1
                tagetIndex = sourceIndex
            }

        } else {
//            print("右滑动")
            progress = 1 - (currentOffsetX / SCREEN_WIDTH - floor(currentOffsetX / SCREEN_WIDTH))

            tagetIndex = Int(currentOffsetX / SCREEN_WIDTH)

            sourceIndex = tagetIndex + 1

            if sourceIndex >= childVcs.count {
                sourceIndex = childVcs.count - 1
            }
        }

//        print("progress\(progress),sourceIndex\(sourceIndex),tagetIndex\(tagetIndex)")
        delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, tagetIndex: tagetIndex)
    }
}

// 对外暴露的方法
extension PageContentView {
    func setCurrentIndex(currentIndex: Int) {
//        记录需要禁止的代理方法
        isForbidScrollDelegate = true

//        滚到正确位置
        let offsetX = CGFloat(currentIndex) * SCREEN_WIDTH
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
    }
}
